using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FiltronASP.Areas.Admin.ViewModels.PageGroups;
using FiltronASP.Areas.Admin.Consts;
using FiltronASP.Helpers.ActionFilters;
using FiltronASP.Helpers.FileUpload;
using FiltronASP.Helpers.Pagination;
using FiltronASP.Helpers.StringExtensions;
using FiltronASP.Models;
using FiltronASP.Models.DAO;
using FiltronASP.Models.DAO.Extensions;
using FiltronASP.Models.DAO.Interfaces;
using FiltronASP.Areas.Admin.Helpers.Permissions;

namespace FiltronASP.Areas.Admin.Controllers
{
    public class PageGroupsController : BaseController
    {
        /// <summary>
        /// klasa odpowiedzialna za operacja na bazie danych, tabela szablonow
        /// </summary>
        protected ITemplateDAO _templateDAO;

        /// <summary>
        /// klasa odpowiedzialna za operacja na bazie danych, tabela stron
        /// </summary>
        protected IPageDAO _pageDAO;

        /// <summary>
        /// klasa odpowiedzialna za operacja na bazie danych, tabela szablonow
        /// </summary>
        protected IPageTypeAcceptableTemplateDAO _pageTypeAcceptableTemplateDAO;

        /// <summary>
        /// klasa odpowiedzialna za operacja na bazie danych, tabela uprawnien do stron
        /// </summary>
        protected IUserPageTypeDAO _userPageTypeDAO;

        /// <summary>
        /// Konstruktor.
        /// </summary>
        public PageGroupsController(ITemplateDAO templateDAO, IPageTypeAcceptableTemplateDAO pageTypeAcceptableTemplateDAO,
                        IPageDAO pageDAO, IUserPageTypeDAO userPageTypeDAO) 
            : base()
        {
            this._templateDAO = templateDAO;
            this._pageTypeAcceptableTemplateDAO = pageTypeAcceptableTemplateDAO;
            this._pageDAO = pageDAO;
            this._userPageTypeDAO = userPageTypeDAO;
        }

         /// <summary>
        /// Konstruktor (dependency injection).
        /// </summary>
        public PageGroupsController() 
            : this(new TemplateDAO(), new PageTypeAcceptableTemplateDAO(), 
                new PageDAO(), new UserPageTypeDAO())
        {
        }

        /// <summary>
        /// Metoda pomocnicza do pobierania modelu <code>PageGroupsIndexViewModel</code>.
        /// </summary>
        /// <param name="page">biezaca strona paginacji</param>
        /// <param name="currentLanguageId">id biezacej wersji jezykowej</param>
        /// <returns>odpowiedni model danych</returns>
        private PageGroupsIndexViewModel GetPageGroupsIndexViewModel(int? page, int? currentLanguageId)
        {
            if (page == null)
            {
                page = 1;
            }   //if
            Language currentLanguage = null;
            if (!currentLanguageId.HasValue)
            {
                currentLanguage = this._languageDAO.GetDefaultLanguage(this.GetAuthenticatedUserId());
                if (currentLanguage != null)
                {
                    currentLanguageId = currentLanguage.language_id;
                }   //if
                else
                {
                    currentLanguageId = -1;
                }   //else
            }
            else
            {   //if lang id null
                currentLanguage = this._languageDAO.FindByPK(currentLanguageId);
            }   //else lang id null
            return new PageGroupsIndexViewModel(this.GetLanguagesToDropDown(currentLanguageId),
                        this.GetPageTypesInMenu(currentLanguageId),
                        this.GetMenus(currentLanguageId),
                        this.GetCurrentLanguage(currentLanguageId),
                        Pagination.ToPagedList<PageType>(this._pageTypeDAO.FindByLanguage(currentLanguageId.Value), page.Value),
                        page.Value);
           
        }

        /// <summary>
        /// Metoda pomocnicza do pobierania modelu <code>PageGroupsIndexViewModel</code>.
        /// </summary>
        /// <param name="currentLanguageId">id biezacej wersji jezykowej</param>
        /// <returns>odpowiedni model danych</returns>
        private PageGroupsIndexViewModel GetPageGroupsIndexViewModel(int? currentLanguageId)
        {
            int? page = 1;
            Language currentLanguage = null;
            if (!currentLanguageId.HasValue)
            {
                currentLanguage = this._languageDAO.GetDefaultLanguage(this.GetAuthenticatedUserId());
                if (currentLanguage != null)
                {
                    currentLanguageId = currentLanguage.language_id;
                }   //if
                else
                {
                    currentLanguageId = -1;
                }   //else
            }
            else
            {   //if lang id null
                currentLanguage = this._languageDAO.FindByPK(currentLanguageId);
            }   //else lang id null
            return new PageGroupsIndexViewModel(this.GetLanguagesToDropDown(currentLanguageId),
                    this.GetPageTypesInMenu(currentLanguageId),
                    this.GetMenus(currentLanguageId),
                    this.GetCurrentLanguage(currentLanguageId),
                    Pagination.ToPagedList<PageType>(this._pageTypeDAO.FindByLanguage(currentLanguageId.Value), page.Value),
                    page.Value);

        }

        /// <summary>
        /// Metoda pomocnicza do pobierania modelu <code>PagesEditionViewModel</code>.
        /// </summary>
        /// <param name="pageToOperateWith">biezaca strona</param>
        /// <param name="paginationPage">strona w paginacji</param>
        /// <returns>odpowiedni model danych</returns>
        private PageGroupsEditionViewModel GetPageGroupsEditionViewModel(PageType pageTypeToOperateWith, int? paginationPage, IQueryable<Template> availibleTemplates)
        {
            if (paginationPage == null)
            {
                paginationPage = 1;
            }   //if null
            if (pageTypeToOperateWith == null)
            {
                throw new Exception("PagesController exception: GetPagesEditionViewModel method, pageToOperateWith object null...");
            }   //if null
            int? languageId = pageTypeToOperateWith.language_id;
            if (!languageId.HasValue)
            {
                throw new Exception("PagesController exception: GetPagesEditionViewModel method, languageId null...");
            }   //if null
            return new PageGroupsEditionViewModel(this.GetLanguagesToDropDown(languageId),
                        this.GetPageTypesInMenu(languageId),
                        this.GetMenus(languageId),
                        this.GetCurrentLanguage(languageId),
                        pageTypeToOperateWith,
                        availibleTemplates,
                        paginationPage.Value);
        }

        /// <summary>
        /// Akcja dla wyswietlania listy grup stron.
        /// </summary>
        /// <param name="page">biezaca strona paginacji</param>
        /// <param name="currentLanguageId">aktualna wersja jezykowka</param>
        /// <returns>widok</returns>
        [Authorize]
        public ActionResult Index(int? page, int? currentLanguageId)
        {
            if (!PermissionHelper.HasUserGlobalPermissionAccess(this.GetAuthenticatedUserId()))
            {
                return this.GetAccessDeniedView();
            }   //if
            if (page <= 0)
            {
                page = 1;
            }   //if
            Language currentLanguage = null;
            if (!currentLanguageId.HasValue)
            {
                currentLanguage = this._languageDAO.GetDefaultLanguage(this.GetAuthenticatedUserId());
                if (currentLanguage != null)
                {
                    currentLanguageId = currentLanguage.language_id;
                }   //if
                else
                {
                    currentLanguageId = -1;
                }   //else
            }
            else
            {   //if lang id null
                currentLanguage = this._languageDAO.FindByPK(currentLanguageId);
            }   //else lang id null

            return View(this.GetPageGroupsIndexViewModel(page, currentLanguageId));
        }

        /// <summary>
        /// Tworzenie nowego typu strony.
        /// </summary>
        /// <param name="viewModel">model danych</param>
        /// <returns>widok</returns>
        [AcceptVerbs(HttpVerbs.Post)]
        [Authorize]
        public ActionResult Create(PageGroupsIndexViewModel viewModel)
        {
            if (!PermissionHelper.HasUserGlobalPermissionAccess(this.GetAuthenticatedUserId()))
            {
                return this.GetAccessDeniedView();
            }   //if
            if (viewModel == null)
            {
                Logger.MyLogger.Log("PageGroupsController exception: Create method, viewModel object null...");
                return View("Errors/PageGroupsError", this.GetBaseViewModel(null));
            }   //if null
            if (viewModel.CurrentLanguage == null)
            {
                Logger.MyLogger.Log("PageGroupsController exception: Create method, viewModel.CurrentLanguage object null...");
                return View("Errors/PageGroupsErrorLanguageUndefined", this.GetBaseViewModel(null));
            }   //if null
            PageType newPageType = this.GetNewPageType(viewModel.CurrentLanguage.language_id);
            IQueryable<Template> availibleTemplates = _templateDAO.FindByLang(viewModel.CurrentLanguage.language_id);
            if (newPageType == null)
            {
                Logger.MyLogger.Log("PageGroupsController exception: Create method, new page object null...");
                return View("Errors/PageGroupsError", this.GetBaseViewModel(viewModel.CurrentLanguage.language_id));
            }   //if null
            return View(this.GetPageGroupsEditionViewModel(newPageType, viewModel.PaginationPage, availibleTemplates));
        }

        /// <summary>
        /// Metoda dodajaca nowy typ stron do bazy danych.
        /// </summary>
        /// <param name="languageId">jezyk</param>
        /// <returns>obiekt typu strony</returns>
        private PageType GetNewPageType(int? languageId)
        {
            try
            {
                if ((!languageId.HasValue))
                {
                    Logger.MyLogger.Log("PageGruopsController exception: GetNewPageType method, languageId null...");
                    return null;
                }   //if
                PageType newPageType = new PageType();
                newPageType.language_id = languageId;
                newPageType.page_type_abbr = PageGroupsConsts.DEFAULT_PAGE_TYPE_NAME + this.GetMaxPageTypeId();
                newPageType.page_type_created = DateTime.Now;
                newPageType.page_type_description = "";
                newPageType.page_type_editable = true;
                newPageType.page_type_link = "" + this.GetMaxPageTypeId();
                newPageType.page_type_modified = DateTime.Now;
                newPageType.page_type_name = PageGroupsConsts.DEFAULT_PAGE_TYPE_NAME + this.GetMaxPageTypeId();
                return this._pageTypeDAO.Add(newPageType);
            }   //try
            catch (Exception ex)
            {
                Logger.MyLogger.Log(ex);
                return null;
            }   //catch            
        }

        /// <summary>
        /// Metoda pobierajaca najwyzsze id dla stron.
        /// </summary>
        /// <returns>najwyzsze id dla stron</returns>
        private int GetMaxPageTypeId()
        {
            if (this._pageTypeDAO == null)
            {
                return 1;
            }   //if
            int? maxId = this._pageTypeDAO.SelectMaxId();
            if (maxId == null)
            {
                return 1;
            }   //if
            return maxId.Value + 1;
        }

        /// <summary>
        /// Akcja do zapisu nowego typu strony.
        /// </summary>       
        /// <param name="viewModel">model danych</param>
        /// <param name="collection">parametry z forma</param>
        /// <returns>widok</returns> 

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateOnlyIncomingValues]
        [ValidateInput(false)]
        [Authorize]
        public ActionResult CreateNewPageType(PageGroupsEditionViewModel viewModel, FormCollection formParams)
        {
            if (!PermissionHelper.HasUserGlobalPermissionAccess(this.GetAuthenticatedUserId()))
            {
                return this.GetAccessDeniedView();
            }   //if
            if (viewModel == null)
            {
                Logger.MyLogger.Log("PageGroupsController exception: CreateNewPage method, viewModel object null...");
                return View("Errors/PageGroupsError", this.GetBaseViewModel(null));
            }   //if null
            if (viewModel.CurrentLanguage == null)
            {
                Logger.MyLogger.Log("PageGroupsController exception: CreateNewPage method, viewModel.CurrentLanguage object null...");
                return View("Errors/PageGroupsError", this.GetBaseViewModel(null));
            }   //if null
            if (viewModel.PageTypeToOperateWith == null)
            {
                Logger.MyLogger.Log("PageGroupsController exception: CreateNewPage method, viewModel.PageToOperateWith object null...");
                return View("Errors/PageGroupsError", this.GetBaseViewModel(viewModel.CurrentLanguage.language_id));
            }   //if null
            IQueryable<Template> availibleTemplates = _templateDAO.FindByLang(viewModel.CurrentLanguage.language_id);
            if (ModelState.IsValid)
                {
                    string testContent = formParams.Get("pageTypesTemplates[]");
                    if (!this.IsNameAvailable(viewModel.PageTypeToOperateWith, viewModel.CurrentLanguage.language_id))
                    {
                        ModelState.AddModelError("PageTypeToOperateWith.page_type_name", "Wybrana nazwa już istnieje, proszę wybrać inną.");
                        return View("Create", this.GetPageGroupsEditionViewModel(viewModel.PageTypeToOperateWith, 
                            viewModel.PaginationPage, availibleTemplates));
                    }
                    if (!this.UpdatePageTypesAcceptableTemplate(viewModel.PageTypeToOperateWith, formParams))
                    {
                        return View("Errors/PageGroupsError", this.GetBaseViewModel(viewModel.CurrentLanguage.language_id));
                    }   //if
                    if (!this.UpdatePageType(viewModel.PageTypeToOperateWith))
                    {
                        return View("Errors/PageGroupsError", this.GetBaseViewModel(viewModel.CurrentLanguage.language_id));
                    }   //if

                    return View("Index", this.GetPageGroupsIndexViewModel(viewModel.PaginationPage, viewModel.CurrentLanguage.language_id));
                }   //if
            return View("Create", this.GetPageGroupsEditionViewModel(viewModel.PageTypeToOperateWith, viewModel.PaginationPage, availibleTemplates));
        }

        /// <summary>
        /// Akcja do aktualizowania szablonow dostepnych dla typu strony.
        /// </summary>
        /// <returns>widok</returns>        
        /// <param name="viewModel">model danych</param>
        /// <param name="collection">parametry z forma</param>
        private bool UpdatePageTypesAcceptableTemplate(PageType PageTypeToOperateWith, FormCollection formParams)
        {
            try
            {
                if (formParams == null)
                {
                    Logger.MyLogger.Log("PagesController exception: UpdatePageTypesAcceptableTemplate method, form params null object...");
                    return false;
                }   //if
                if (PageTypeToOperateWith == null)
                {
                    Logger.MyLogger.Log("PageGroupsController exception: UpdatePageTypesAcceptableTemplate method, PageTypeToOperateWith null...");
                    return false;
                }   //if null
                String acceptableTemplates = formParams.Get(PageGroupsConsts.ACCEPTABLE_TEMPLATES_REQUEST_PARAM);
                if (String.IsNullOrEmpty(acceptableTemplates)) 
                {
                    return true;
                }   //if
                String[] acceptableTemplateIds = acceptableTemplates.Split(',');
                if (acceptableTemplateIds == null)
                {
                    return true;
                }   //if
                if (!this.DeletePageTypesAcceptableTemplate(PageTypeToOperateWith)) 
                {
                    Logger.MyLogger.Log("PageGroupsController exception: UpdatePageTypesAcceptableTemplate method, unable to delete templates...");
                    return false;
                }   //if
                foreach (string acceptableTemplateId in acceptableTemplateIds)
                {
                    PageTypeAcceptableTemplate newPageTemplate = new PageTypeAcceptableTemplate();
                    newPageTemplate.page_type_template_created = DateTime.Now;
                    newPageTemplate.page_type_template_modified = DateTime.Now;
                    newPageTemplate.template_id = Int32.Parse(acceptableTemplateId);
                    newPageTemplate.page_type_id = PageTypeToOperateWith.page_type_id;
                    if (this._pageTypeAcceptableTemplateDAO.Add(newPageTemplate) == null)
                    {   
                        Logger.MyLogger.Log("PageGroupsController exception: UpdatePageTypesAcceptableTemplate method, unable to add page_template to database...");
                        return false;
                    }   //if null
                }   //foreach
                return true;
            }
            catch (Exception ex)
            {
                Logger.MyLogger.Log(ex);
                return false;
            }   //catch            
        }

        /// <summary>
        /// Usuwanie wskazanych szablonow.
        /// </summary>
        /// <returns>widok</returns>        
        /// <param name="viewModel">model danych</param>
        /// <param name="collection">parametry z forma</param>
        private bool DeletePageTypesAcceptableTemplate(PageType PageTypeToOperateWith)
        {
            if (PageTypeToOperateWith == null)
            {
                Logger.MyLogger.Log("PageGroupsController exception: DeletePageTypesAcceptableTemplate method, PageTypeToOperateWith null...");
                return false;
            }   //if null
            if (this._pageTypeAcceptableTemplateDAO.FindByPage(PageTypeToOperateWith.page_type_id) == null)
            {
                return true;
            }
            return this._pageTypeAcceptableTemplateDAO.DeleteByPageType(PageTypeToOperateWith.page_type_id);
        }

        /// <summary>
        /// Usuwanie wskazanych uprawnien.
        /// </summary>
        /// <returns>true/false</returns>        
        /// <param name="PageTypeToOperateWith">grupa stron</param>
        private bool DeleteUserPageTypes(PageType PageTypeToOperateWith)
        {
            if (PageTypeToOperateWith == null)
            {
                Logger.MyLogger.Log("PageGroupsController exception: DeleteUserPageTypes method, PageTypeToOperateWith null...");
                return false;
            }   //if null
            return this._userPageTypeDAO.DeleteByPageTypeId(PageTypeToOperateWith.page_type_id);
        }

        /// <summary>
        /// Metoda do aktualizacji typu strony w bazie na podstawie zadania.
        /// </summary>
        /// <param name="pageTypeFromRequest">typ strony z modelu danych z zadania</param>
        /// <returns>true, gdy sie uda, false wpp</returns>
        private bool UpdatePageType(PageType pageTypeFromRequest)
        {
            if (pageTypeFromRequest == null)
            {
                return false;
            }   //if null
            PageType pageTypeToUpdate = this._pageTypeDAO.FindByPK(pageTypeFromRequest.page_type_id);
            if (pageTypeToUpdate == null)
            {
                Logger.MyLogger.Log("PageGroupsController exception: UpdatePageType method, unable to find page type to update...");
                return false;
            }   //if null
            pageTypeToUpdate.page_type_name = pageTypeFromRequest.page_type_name;
            return this._pageTypeDAO.SubmitChanges();
        }

        /// <summary>
        /// Metoda usuwajaca typ strony (i zaleznosci).
        /// </summary>
        /// <param name="viewModel">model danych</param>
        /// <returns>odpowiedni widok</returns>
        [AcceptVerbs(HttpVerbs.Post)]
        [Authorize]
        public ActionResult DeleteConfirmed(PageGroupsEditionViewModel viewModel)
        {
            if (!PermissionHelper.HasUserGlobalPermissionAccess(this.GetAuthenticatedUserId()))
            {
                return this.GetAccessDeniedView();
            }   //if
            if (viewModel == null)
            {
                Logger.MyLogger.Log("PageGroupsController exception: DeleteConfirmed method, viewModel object null...");
                return View("Errors/PageGroupsError", this.GetBaseViewModel(null));
            }   //if null
            if (viewModel.CurrentLanguage == null)
            {
                Logger.MyLogger.Log("PageGroupsController exception: DeleteConfirmed method, viewModel.CurrentLanguage object null...");
                return View("Errors/PageGroupsError", this.GetBaseViewModel(null));
            }   //if null
            if (viewModel.PageTypeToOperateWith == null)
            {
                Logger.MyLogger.Log("PageGroupsController exception: DeleteConfirmed method, viewModel.PageTypeToOperateWith object null...");
                return View("Errors/PageGroupsError", this.GetBaseViewModel(viewModel.CurrentLanguage.language_id));
            }   //if null
            try
            {
                PageType pageTypeToDelete = this._pageTypeDAO.FindByPK(viewModel.PageTypeToOperateWith.page_type_id);
                if (pageTypeToDelete == null)
                {
                    Logger.MyLogger.Log("PageGroupsController exception: DeleteConfirmed method, page type object null...");
                    return View("Errors/PageGroupsError", this.GetBaseViewModel(viewModel.CurrentLanguage.language_id));
                }   //if
                if (!this.DeletePageTypesAcceptableTemplate(viewModel.PageTypeToOperateWith))
                {
                    Logger.MyLogger.Log("PageGroupsController exception: DeletePageTypesAcceptableTemplate method, unable to delete...");
                    return View("Errors/PageGroupsError", this.GetBaseViewModel(viewModel.CurrentLanguage.language_id));
                }   //if
                if (!this.DeleteUserPageTypes(viewModel.PageTypeToOperateWith))
                {
                    Logger.MyLogger.Log("PageGroupsController exception: DeleteUserPageTypes method, unable to delete...");
                    return View("Errors/PageGroupsError", this.GetBaseViewModel(viewModel.CurrentLanguage.language_id));
                }   //if
                if (this._pageTypeDAO.Delete(pageTypeToDelete.page_type_id))
                {
                    if (this._pageTypeDAO.SubmitChanges())
                    {
                        return View("Index", this.GetPageGroupsIndexViewModel(viewModel.PaginationPage,
                            viewModel.CurrentLanguage.language_id));
                    }   //if submit
                }   //if
                Logger.MyLogger.Log("PageGroupsController exception: DeleteConfirmed method, unable to delete page type...");
                return View("Errors/PageGroupsError", this.GetBaseViewModel(viewModel.CurrentLanguage.language_id));
            }   //catch
            catch (Exception ex)
            {
                Logger.MyLogger.Log(ex);
                return View("Errors/PageGroupsError", this.GetBaseViewModel(viewModel.CurrentLanguage.language_id));
            }   //catch
        }

        /// <summary>
        /// Metoda anulujaca akcje dodawania nowej strony. 
        /// </summary>
        /// <param name="viewModel">model danych</param>
        /// <returns>odpowiedni widok</returns>
        [Authorize]
        public ActionResult CancelNewPageType(PageGroupsEditionViewModel viewModel)
        {
            if (!PermissionHelper.HasUserGlobalPermissionAccess(this.GetAuthenticatedUserId()))
            {
                return this.GetAccessDeniedView();
            }   //if
            if (viewModel == null)
            {
                Logger.MyLogger.Log("PageGroupsController exception: CancelNewPageType method, viewModel object null...");
                return View("Errors/PageGroupsError", this.GetBaseViewModel(null));
            }   //if null
            if (viewModel.CurrentLanguage == null)
            {
                Logger.MyLogger.Log("PageGroupsController exception: CancelNewPageType method, viewModel.CurrentLanguage object null...");
                return View("Errors/PageGroupsError", this.GetBaseViewModel(null));
            }   //if null
            if (viewModel.PageTypeToOperateWith == null)
            {
                Logger.MyLogger.Log("PageGroupsController exception: CancelNewPageType method, viewModel.PageTypeToOperateWith object null...");
                return View("Errors/PageGroupsError", this.GetBaseViewModel(viewModel.CurrentLanguage.language_id));
            }   //if null
            try
            {
                return this.DeleteConfirmed(viewModel);
            }   //try
            catch (Exception ex)
            {
                Logger.MyLogger.Log(ex);
                return View("Errors/PageGroupsError", this.GetBaseViewModel(viewModel.CurrentLanguage.language_id));
            }   //catch
        }

        /// <summary>
        /// Usuniecie grupy stron.
        /// </summary>
        /// <param name="currentLanguageId">wersja jezykowa</param>
        /// <param name="pageTypeToDeleteId">id strony</param>
        /// <param name="paginationPage">strona w paginacji</param>
        /// <returns>widok</returns>
        [Authorize]
        public ActionResult DeletePageGroup(int? pageTypeToDeleteId, int? currentLanguageId, int? paginationPage)
        {
            if (!PermissionHelper.HasUserGlobalPermissionAccess(this.GetAuthenticatedUserId()))
            {
                return this.GetAccessDeniedView();
            }   //if
            if (currentLanguageId == null)
            {
                Logger.MyLogger.Log("PageGroupsController exception: DeletePageType method, currentLanguageId object null...");
                return View("Errors/PageGroupsError", this.GetBaseViewModel(null));
            }   //if null
            if ((pageTypeToDeleteId == null) || (pageTypeToDeleteId <= 0))
            {
                Logger.MyLogger.Log("PageGroupsController exception: DeletePageType method, pageTypeToDeleteId object null...");
                return View("Errors/PageGroupsError", this.GetBaseViewModel(currentLanguageId));
            }   //if null
            try
            {
                PageType pageTypeToDelete = this._pageTypeDAO.FindByPK(pageTypeToDeleteId);
                if (pageTypeToDelete == null)
                {
                    Logger.MyLogger.Log("PageGroupsController exception: DeletePageType method, page type object null...");
                    return View("Errors/PageGroupsError", this.GetBaseViewModel(currentLanguageId));
                }   //if
                if (this.PageGroupHasChildren(pageTypeToDeleteId))
                {
                    return View("DeletePageGroupWithChildren", this.GetPageGroupsEditionViewModel(pageTypeToDelete, paginationPage, null));
                }   //if
                return View(this.GetPageGroupsEditionViewModel(pageTypeToDelete, paginationPage, null));
            }   //try
            catch (Exception ex)
            {
                Logger.MyLogger.Log(ex);
                return View("Errors/PageGroupsError", this.GetBaseViewModel(currentLanguageId));
            }   //catch
        }

        /// <summary>
        /// Sprawdzanie czy dany login juz istnieje
        /// </summary>
        /// <param name="login">login</param>
        /// <returns>true jesli login jest dostepny, false wpp</returns>
        private bool IsNameAvailable(PageType pageTypeFromRequest, int? currentLanguageId)
        {
            if (pageTypeFromRequest == null)
            {
                Logger.MyLogger.Log("PageGroupsController exception: IsNameAvailable method, page type object null...");
                return false;
            }   //if null
            if (!currentLanguageId.HasValue)
            {
                Logger.MyLogger.Log("PageGroupsController exception: IsNameAvailable method, language id null...");
                return false;
            }   //if null
            if (_pageTypeDAO.FindByNameAndLanguageAndNoPageTypeId(pageTypeFromRequest.page_type_name, currentLanguageId.Value, pageTypeFromRequest.page_type_id) == null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// Tworzenie nowego typu strony.
        /// </summary>
        /// <param name="viewModel">model danych</param>
        /// <returns>widok</returns>
        [Authorize]
        public ActionResult EditPageGroup(int? pageTypeToEditId, int? currentLanguageId, int? paginationPage)
        {
            if (!PermissionHelper.HasUserGlobalPermissionAccess(this.GetAuthenticatedUserId()))
            {
                return this.GetAccessDeniedView();
            }   //if
            if (currentLanguageId == null)
            {
                Logger.MyLogger.Log("PageGroupsController exception: EditPageGroup method, currentLanguageId object null...");
                return View("Errors/PageGroupsError", this.GetBaseViewModel(null));
            }   //if null
            if ((pageTypeToEditId == null) || (pageTypeToEditId <= 0))
            {
                Logger.MyLogger.Log("PageGroupsController exception: EditPageGroup method, pageTypeToDeleteId object null...");
                return View("Errors/PageGroupsError", this.GetBaseViewModel(currentLanguageId));
            }   //if null
            IQueryable<Template> availibleTemplates = _templateDAO.FindByLang(currentLanguageId ?? 0);
            try
            {
                PageType pageTypeToEdit = this._pageTypeDAO.FindByPK(pageTypeToEditId);
                if (pageTypeToEdit == null)
                {
                    Logger.MyLogger.Log("PageGroupsController exception: EditPageGroup method, page type object null...");
                    return View("Errors/PageGroupsError", this.GetBaseViewModel(currentLanguageId));
                }   //if
                return View(this.GetPageGroupsEditionViewModel(pageTypeToEdit, paginationPage, availibleTemplates)); 
            }   //try
            catch (Exception ex)
            {
                Logger.MyLogger.Log(ex);
                return View("Errors/PageGroupsError", this.GetBaseViewModel(currentLanguageId));
            }   //catch
        }

        /// <summary>
        /// Akcja do zapisu zedytowanej grupy stron.
        /// </summary>
        /// <param name="language_id">klucz glowny tabeli</param>
        /// <param name="collection">parametry z forma</param>
        /// <returns>widok</returns>
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateOnlyIncomingValues]
        [ValidateInput(false)]
        [Authorize]
        public ActionResult SubmitPageGroup(PageGroupsEditionViewModel viewModel, FormCollection formParams)
        {
            if (!PermissionHelper.HasUserGlobalPermissionAccess(this.GetAuthenticatedUserId()))
            {
                return this.GetAccessDeniedView();
            }   //if
            if (viewModel == null)
            {
                Logger.MyLogger.Log("PageGroupsController exception: SubmitPageGroup method, viewModel object null...");
                return View("Errors/PageGroupsError", this.GetBaseViewModel(null));
            }   //if null
            if (viewModel.CurrentLanguage == null)
            {
                Logger.MyLogger.Log("PageGroupsController exception: SubmitPageGroup method, viewModel.CurrentLanguage object null...");
                return View("Errors/PageGroupsError", this.GetBaseViewModel(null));
            }   //if null
            if (viewModel.PageTypeToOperateWith == null)
            {
                Logger.MyLogger.Log("PageGroupsController exception: SubmitPageGroup method, viewModel.PageToOperateWith object null...");
                return View("Errors/PageGroupsError", this.GetBaseViewModel(viewModel.CurrentLanguage.language_id));
            }   //if null
            IQueryable<Template> availibleTemplates = _templateDAO.FindByLang(viewModel.CurrentLanguage.language_id);
            if (ModelState.IsValid)
            {
                if (!this.IsNameAvailable(viewModel.PageTypeToOperateWith, viewModel.CurrentLanguage.language_id))
                {
                    ModelState.AddModelError("PageTypeToOperateWith.page_type_name", "ta nazwa już istnieje, wybierz inną");
                    return View("EditPageGroup", this.GetPageGroupsEditionViewModel(viewModel.PageTypeToOperateWith,
                        viewModel.PaginationPage, availibleTemplates));
                }
                if (!this.UpdatePageTypesAcceptableTemplate(viewModel.PageTypeToOperateWith, formParams))
                {
                    return View("Errors/PageGroupsError", this.GetBaseViewModel(viewModel.CurrentLanguage.language_id));
                }   //if
                if (!this.UpdatePageType(viewModel.PageTypeToOperateWith))
                {
                    return View("Errors/PageGroupsError", this.GetBaseViewModel(viewModel.CurrentLanguage.language_id));
                }   //if

                return View("Index", this.GetPageGroupsIndexViewModel(viewModel.PaginationPage, viewModel.CurrentLanguage.language_id));
            }   //if
            return View("EditPageGroup", this.GetPageGroupsEditionViewModel(viewModel.PageTypeToOperateWith, viewModel.PaginationPage, availibleTemplates));
        }

        /// <summary>
        /// Metoda odpowiadajaca za operacje zmiany wersji jezykowej w drop downie.
        /// </summary>
        /// <param name="viewModel">model danych</param>
        /// <returns>odpowiedni widok</returns>
        [Authorize]
        public ActionResult ChangeLanguage(PageGroupsIndexViewModel viewModel)
        {
            if (viewModel == null)
            {
                Logger.MyLogger.Log("PageGroupsController exception: ChangeLanguage method, viewModel object null...");
                return View("Errors/PageGroupsError", this.GetBaseViewModel(null));
            }   //if null
            return View("Index", this.GetPageGroupsIndexViewModel(viewModel.DropDownLanguageId));
        }

        /// <summary>
        /// Metoda sprawdzajaca czy sa strony w grupie.
        /// </summary>
        /// <param name="menuItemId">id grupy stron</param>
        private bool PageGroupHasChildren(int? pageTypeId)
        {
            try
            {
                if (pageTypeId == null)
                {
                    Logger.MyLogger.Log("PageGroupsController exception: PageGroupHasChildren method, pageTypeId null...");
                    return false;
                }   //if null
                return (this._pageDAO.FindByPageType(pageTypeId.Value) != null);
            }   //try
            catch (Exception ex)
            {
                Logger.MyLogger.Log(ex);
                return false;
            }   //catch
        }

    }
}
